/**
 * L.Chen
 * company : hisun
 */

Ext.ns('Ext.hisun.form')
Ext.hisun.form.width=200;
Ext.TreeComboField = Ext.extend(Ext.form.TriggerField, {
	valueField : "id",
	displayField : "name",
	haveShow : false,
	editable : false,
	minListWidth : 170,
	maxHeight : 300,
	dataUrl : 'dept!getDeptTree.action',
	listAlign : 'tl-bl?',
	shadow : true,
	onTriggerClick : function() {
		if (this.disabled) {
			return;
		}
		if (this.isExpanded()) {
			this.collapse();
		} else {
			this.expand();
		}

	},
	isExpanded : function() {
		return this.list && this.list.isVisible();
	},
	initComponent : function() {
		Ext.TreeComboField.superclass.initComponent.call(this);
		this.addEvents('expand', 'collapse');
		this.tree = new Ext.tree.TreePanel({
			id : Ext.id(),
			monitorResize : true,
			autoHeight : true,
			autoWidth : true,
			autoScroll : false,
			rootVisible : false,
			lines : true,
			border : false,
			containerScroll : true,
			singleExpand : true,
			useArrows : false,
			loader : new Ext.tree.TreeLoader({
				dataUrl : this.dataUrl,
				root:'list'
				
			}),
			root : new Ext.tree.AsyncTreeNode()
		});
	},

	onRender : function(ct, position) {
		Ext.TreeComboField.superclass.onRender.call(this, ct, position);
		if (!this.list) {
			var cls = 'x-combo-list';
			this.list = new Ext.Layer({
				shadow : this.shadow,
				constrain : false,
				shim : false,
				cls : cls
			});
			var lw = this.listWidth
					|| Math.max(this.wrap.getWidth(), this.minListWidth);
			this.list.setWidth(lw);
			this.list.swallowEvent('mousewheel');
			this.assetHeight = 0;
			if (this.title) {
				this.header = this.list.createChild({
					cls : cls + '-hd',
					html : this.title
				});
				this.assetHeight += this.header.getHeight();
			}

			this.innerList = this.list.createChild({
				//autoHeight : true,
				cls : cls + '-inner',
				style : "height:100%;background:white;"
					// :"overflow:auto;background:white;position:relative;zoom:1"
					});
			// this.innerList.setWidth(lw + 25);
			//this.innerList.setHeight(350);
			this.list.applyStyles({background:"white"});
			this.tree.render(this.innerList);
			this.list.beginUpdate();
			var pad = this.list.getFrameWidth('tb')
					+ (this.resizable ? this.handleHeight : 0)
					+ this.assetHeight;
			this.list.setHeight(350 + pad);
			this.list.endUpdate();
		}
		this.tree.on("click", this.choice, this);
		this.tree.on("dblclick", function() {
			this.list.hide();
		}, this);
		this.tree.on("load", function(node) {
			if (node.id == this.getValue()) {
				this.setValue(this.value);
			}
		}, this);
		if (this.hiddenName) {
			this.hiddenField = this.el.insertSibling({
				tag : 'input',
				type : 'hidden',
				name : this.hiddenName,
				id : (this.hiddenId || this.hiddenName)
			}, 'before', true);
			this.hiddenField.value = this.hiddenValue !== undefined
					? this.hiddenValue
					: this.value !== undefined ? this.value : '';
			this.el.dom.removeAttribute('name');
		}
		if (!this.editable) {
			this.editable = true;
			this.setEditable(false);
		}
	},
	getValue : function() {
		return typeof this.value != 'undefined' ? this.value : '';
	},
	getLabel:function(){
		return Ext.TreeComboField.superclass.getValue.call(this);
	},
	clearValue : function() {
		if (this.hiddenField) {
			this.hiddenField.value = '';
		}
		this.setRawValue('');
		this.lastSelectionText = '';
		this.applyEmptyText();
	},
	readPropertyValue : function(obj, p) {
		var v = null;
		for (var o in obj) {
			if (o == p)
				v = obj[o];
		}
		return v;
	},
	restrictHeight : function() {
		this.innerList.dom.style.height = '';
		var inner = this.innerList.dom;

		var pad = this.list.getFrameWidth('tb')
				+ (this.resizable ? this.handleHeight : 0) + this.assetHeight;
		var h = Math.max(inner.clientHeight, inner.offsetHeight,
				inner.scrollHeight);
		var ha = this.getPosition()[1] - Ext.getBody().getScroll().top;

		var hb = Ext.lib.Dom.getViewHeight() - ha - this.getSize().height;

		var space = Math.max(ha, hb, this.minHeight || 0)
				- this.list.shadowOffset - pad - 5;

		h = Math.min(h, space, this.maxHeight);
		h = h < 350 ? 350 : h;
		//this.innerList.setHeight(h);
		this.list.beginUpdate();
		this.list.setHeight(h + pad);
		this.list.alignTo(this.wrap, this.listAlign);
		this.list.endUpdate();
	},
	setValue : function(obj) {
		if (!obj) {
			this.clearValue();
			return;
		}
		var v = obj;
		var text = v;
		var value = this.valueField || this.displayField;
		if (typeof v == "object" && this.readPropertyValue(obj, value)) {
			text = obj[this.displayField || this.valueField];
			v = obj[value];
		}

		var node = this.tree.getNodeById(v);
		if (!node && v) {
			var v_str = v.toString();
			var path = this.tree.root.getPath();
			var childNodes = this.tree.root.childNodes;
			var start_pos;
			for (i = 0; i < childNodes.length; i++) {
				if (v_str.match(eval("/^(" + childNodes[i].id + ")/"))) {
					path = childNodes[i].getPath();
					start_pos = childNodes[i].id.toString().length;
				}
			}
			if (v_str.length % 2 == 0) {
				for (i = start_pos / 2; i < v_str.length / 2; i++) {
					path += "/" + v_str.substr(0, (i + 1) * 2);
				}
				this.tree.selectPath(path);
				
				node = this.tree.getNodeById(v);
			}
		}
		
		if (node) {
			text = node.text;
			this.tree.selectPath(node.getPath())
		} else if (this.valueNotFoundText !== undefined) {
			text = this.valueNotFoundText;
		}
		this.lastSelectionText = text;
		if (this.hiddenField) {
			this.hiddenField.value = v;
		}
		
		Ext.TreeComboField.superclass.setValue.call(this, text);
		this.value = v;
		
	},
	setEditable : function(value) {
		if (value == this.editable) {
			return;
		}
		this.editable = value;
		if (!value) {
			this.el.dom.setAttribute('readOnly', true);
			this.el.on('mousedown', this.onTriggerClick, this);
			this.el.addClass('x-combo-noedit');
		} else {
			this.el.dom.setAttribute('readOnly', false);
			this.el.un('mousedown', this.onTriggerClick, this);
			this.el.removeClass('x-combo-noedit');
		}
	},
	choice : function(node, eventObject) {
		this.fireEvent("select", this, node, eventObject)
		if (node.id != "root")
			this.setValue(node.id);
		else
			this.clearValue();
	},
	onDestroy : function() {
		if (this.tree.rendered) {
			this.tree.getEl().remove();
		}
		Ext.TreeComboField.superclass.onDestroy.call(this);
	},
	collapse : function() {
		if (this.list.hidden) {
			return;
		}
		this.list.hide();
		Ext.getDoc().un('mousewheel', this.collapseIf, this);
		Ext.getDoc().un('mousedown', this.collapseIf, this);
		this.fireEvent('collapse', this);
	},

	collapseIf : function(e) {
		if (!e.within(this.wrap) && !e.within(this.list)) {
			this.collapse();
		}
	},

	expand : function() {
		if (this.minListWidth && this.minListWidth < this.wrap.getWidth())
			this.list.setWidth(this.wrap.getWidth());
		this.list.alignTo(this.wrap, this.listAlign);
		this.list.show();
		this.list.setOverflow('auto');
		this.restrictHeight();
		Ext.getDoc().on('mousewheel', this.collapseIf, this);
		Ext.getDoc().on('mousedown', this.collapseIf, this);
		this.fireEvent('expand', this);
	}
});
Ext.hisun.DeptCombo = Ext.extend(Ext.TreeComboField, {
	dataUrl:Ext.WEB_CONTEXT+'/jsp/admin/power/Depgroup_findDept.action',
	width:Ext.hisun.form.width
});
Ext.override(Ext.tree.TreeLoader, {
	processResponse : function(response, node, callback){
	    var json = response.responseText;
	    try {
	        var o = eval("("+json+")");
	        if (this.root){
	        	o=o[this.root]
	        }
	        node.beginUpdate();
	        for(var i = 0, len = o.length; i < len; i++){
	            var n = this.createNode(o[i]);
	            if(n){
	                node.appendChild(n);
	            }
	        }
	        node.endUpdate();
	        if(typeof callback == "function"){
	            callback(this, node);
	        }
	    }catch(e){
	        this.handleFailure(response);
	    }
	}
});
Ext.hisun.PersonCombo = Ext.extend(Ext.form.ComboBox,{
	 initComponent : function(){
		Ext.hisun.PersonCombo.superclass.initComponent.call(this);
		this.store =new Ext.data.JsonStore({
		    fields: ['id', 'realityname'],
		    root:'list',autoLoad:true,url:Ext.WEB_CONTEXT+'/jsp/admin/power/Appuser_findPerson.action'
		});
	 },
	 displayField:'realityname',valueField :'id',mode: 'local',width:Ext.hisun.form.width
});
